//! 哈希工具
//! 
//! 提供各种哈希算法的统一接口和工具函数

use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;
use fxhash::FxHasher;

/// 哈希算法枚举
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HashAlgorithm {
    /// 标准库 SipHash
    SipHash,
    /// FxHash 高性能算法
    FxHash,
    /// CRC32 算法
    Crc32,
}

/// 哈希工具类
pub struct HashUtils;

impl HashUtils {
    /// 使用指定算法计算哈希值
    pub fn hash_with_algorithm<T: Hash>(value: &T, algorithm: HashAlgorithm) -> u64 {
        match algorithm {
            HashAlgorithm::SipHash => {
                let mut hasher = DefaultHasher::new();
                value.hash(&mut hasher);
                hasher.finish()
            }
            HashAlgorithm::FxHash => {
                let mut hasher = FxHasher::default();
                value.hash(&mut hasher);
                hasher.finish()
            }
            HashAlgorithm::Crc32 => {
                // 简化实现，实际可以使用 crc32fast crate
                let mut hasher = DefaultHasher::new();
                value.hash(&mut hasher);
                hasher.finish()
            }
        }
    }

    /// 快速哈希（使用 FxHash）
    pub fn fast_hash<T: Hash>(value: &T) -> u64 {
        Self::hash_with_algorithm(value, HashAlgorithm::FxHash)
    }

    /// 安全哈希（使用 SipHash）
    pub fn secure_hash<T: Hash>(value: &T) -> u64 {
        Self::hash_with_algorithm(value, HashAlgorithm::SipHash)
    }

    /// 比较两个哈希算法的性能
    pub fn benchmark_hash_algorithms<T: Hash + Clone>(value: &T, iterations: usize) -> (u64, u64, u64) {
        let start = std::time::Instant::now();
        for _ in 0..iterations {
            Self::hash_with_algorithm(value, HashAlgorithm::SipHash);
        }
        let sip_time = start.elapsed().as_nanos() as u64;

        let start = std::time::Instant::now();
        for _ in 0..iterations {
            Self::hash_with_algorithm(value, HashAlgorithm::FxHash);
        }
        let fx_time = start.elapsed().as_nanos() as u64;

        let start = std::time::Instant::now();
        for _ in 0..iterations {
            Self::hash_with_algorithm(value, HashAlgorithm::Crc32);
        }
        let crc_time = start.elapsed().as_nanos() as u64;

        (sip_time, fx_time, crc_time)
    }
}

